<template>
  <div id="konvacontainer"></div>
</template>

<script>
import Konva from 'konva';
import alarmImg from '@/assets/tip.png'; // 引入告警图片

// 模拟测试数据
const dcPowerData = [
  {
    id: 1,
    name: '直流柜1',
    voltage: 48,
    current: 10,
    power: 480,
    status: '正常',
    x: 100,
    y: 200
  },
  {
    id: 2,
    name: '直流柜2',
    voltage: 0,
    current: 0,
    power: 0,
    status: '告警',
    x: 300,
    y: 200
  }
];

export default {
  mounted() {
    this.initKonva();
  },
  methods: {
    initKonva() {
      const stage = new Konva.Stage({
        container: 'konvacontainer',
        width: window.innerWidth,
        height: window.innerHeight
      });

      const layer = new Konva.Layer();

      // 绘制直流柜及相关信息
      dcPowerData.forEach((dc柜) => {
        this.drawDCCabinet(layer, dc柜);
      });

      // 假设这里有一个总的进线点，连接所有直流柜
      const mainIncomingX = 50;
      const mainIncomingY = 100;
      dcPowerData.forEach((dc柜, index) => {
        const x1 = mainIncomingX;
        const y1 = mainIncomingY;
        const x2 = dc柜.x + dc柜.width / 2;
        const y2 = dc柜.y;
        this.drawLine(layer, x1, y1, x2, y2);
      });

      stage.add(layer);
    },
    drawDCCabinet(layer, dc柜) {
      const width = 100;
      const height = 80;
      const rect = new Konva.Rect({
        x: dc柜.x,
        y: dc柜.y,
        width,
        height,
        fill: dc柜.status === '正常'? 'lightgray' : 'lightcoral',
        stroke: 'black',
        strokeWidth: 1
      });
      layer.add(rect);

      // 绘制电压、电流、功率信息
      const textConfig = {
        x: dc柜.x + 10,
        y: dc柜.y + 10,
        fontSize: 12,
        fontFamily: 'Arial',
        fill: 'black'
      };

      const voltageText = new Konva.Text({
       ...textConfig,
        text: `电压: ${dc柜.voltage}V`
      });
      layer.add(voltageText);

      const currentText = new Konva.Text({
       ...textConfig,
        y: dc柜.y + 25,
        text: `电流: ${dc柜.current}A`
      });
      layer.add(currentText);

      const powerText = new Konva.Text({
       ...textConfig,
        y: dc柜.y + 40,
        text: `功率: ${dc柜.power}W`
      });
      layer.add(powerText);

      // 如果状态为告警，绘制告警图片
      if (dc柜.status === '告警') {
        const imageObj = new Image();
        imageObj.src = alarmImg;
        imageObj.onload = () => {
          const alarmImage = new Konva.Image({
            x: dc柜.x + width - 20,
            y: dc柜.y + 10,
            image: imageObj,
            width: 20,
            height: 20
          });
          layer.add(alarmImage);
        };
      }

      dc柜.width = width;
      dc柜.height = height;
    },
    drawLine(layer, x1, y1, x2, y2) {
      const line = new Konva.Line({
        points: [x1, y1, x2, y2],
        stroke: 'blue',
        strokeWidth: 2
      });
      layer.add(line);
    }
  }
};
</script>

<style scoped>
#konvacontainer {
  width: 100%;
  height: 100%;
}
</style>